<template>
	<view>
		<!-- 搜索框 -->
		<u-search v-model="searchVal" :placeholder="placeholder || '请输入关键词'" :show-action="true" action-text="取消"
			margin="20rpx 24rpx" clearabled @change="onChange" @search="onSearch" @custom="onCustom">
		</u-search>

		<template v-if="showMode === 1">
			<!-- 标签模块 -->
			<MyTags text="历史记录" showIcon :list="historyList" @clickTag="clickTag" @clickIcon="onDeleteHistory"></MyTags>

			<!-- 标签模块 -->
			<MyTags text="热门搜索" :showIcon="false" :list="hotList" @clickTag="clickTag"></MyTags>
		</template>

		<template v-else>
			<!-- 搜索列表 -->
			<view v-show="showMode === 2">
				<u-cell-group>
					<u-cell-item v-for="(item,index) in searchList" :title="item" :arrow="false" :key="index"
						@click="clickSearchItem(item)"></u-cell-item>
					</u-cell-item>
				</u-cell-group>
				<!-- 提示，没有更多了，或者是，暂无搜索数据 -->
				<u-loadmore status="nomore" :load-text="{nomore:searchList.length === 0 ? '暂无数据' : '没有更多了'}" />
			</view>

			<!-- 加载中：还没拿到商品的列表数据
			暂无数据：已经拿到列表数据且为空
			列表：已经拿到列表数据且不为空
			没有更多：已经拿到列表数据且不为空且已经加载完毕 -->

			<!-- 商品列表 -->
			<view v-show="showMode === 3">
				<!-- 加载中 -->
				<u-loadmore v-if="!hasFetchedGoodsList" status="loading" margin-top="50" />

				<!-- 暂无数据 -->
				<u-loadmore v-if="hasFetchedGoodsList && !goodsList.length" status="nomore" margin-top="50"
					:load-text="{nomore:'暂无数据'}" />

				<template v-if="hasFetchedGoodsList && goodsList.length">
					<u-dropdown>
						<u-dropdown-item title="综合" disabled></u-dropdown-item>
						<u-dropdown-item v-model="dropdownVal1" title="价格" :options="options1"
							@change="onChangeDropdownVal1"></u-dropdown-item>
						<u-dropdown-item v-model="dropdownVal2" title="分类" :options="options2"
							@change="onChangeDropdownVal2"></u-dropdown-item>
					</u-dropdown>
					<view class="goods-list">
						<view v-for="item in goodsList" class="item" :key="item.id">
							<view class="img">
								<view class="inner">
									<u-image showLoading width="100%" height="100%" :src="item.list_pic_url">
									</u-image>
								</view>
							</view>
							<view class="text">{{item.name}}</view>
							<view class="price">人民币{{item.retail_price.toFixed(2)}}元</view>
						</view>
					</view>
				</template>

				<!-- 没有更多了 -->
				<view v-if="hasFetchedGoodsList && goodsList.length && currentPage === totalPages"
					style="padding-bottom: 50rpx;">
					<u-loadmore status="nomore" margin-top="50" />
				</view>


			</view>
		</template>
	</view>
</template>

<script>
	let timer = null
	export default {
		data() {
			return {
				placeholder: '',
				historyList: [], // 历史记录
				hotList: [], // 热门搜索
				searchVal: '',
				showMode: 1, // 1标签模块 2搜索列表 3商品列表
				searchList: [], // 搜索列表
				doNotShowSearchList: false, // ；用来判断要不要显示搜索列表
				goodsList: [], //商品列表
				currentPage: 1, // 当前是第几页的数据
				totalPages: 0, // 总共有多少页数据
				dropdownVal1: '',
				dropdownVal2: '',
				options1: [{
						label: '价格由高到低',
						value: 'desc',
					},
					{
						label: '价格由低到高',
						value: 'asc',
					}
				],
				options2: [],
				sort: 'id', // 排序依据
				order: '', // 价格的值
				categoryId: '', // 分类的值
				hasFetchedGoodsList: false //  是否已经获取到了商品列表数据
			};
		},
		onLoad() {
			this.handleSearchIndex()
		},
		onUnload() {
			// 页面销毁的时候清除定时器
			clearTimeout(timer)
		},
		// 触底加载更多
		onReachBottom() {
			if (this.currentPage < this.totalPages) {
				this.currentPage += 1
				this.requestGoodsList()
			}
		},
		methods: {
			handleSearchIndex() {
				this.$request({
					url: 'search/index',
					successCb: res => {
						console.log(res)
						let {
							defaultKeyword,
							historyKeywordList,
							hotKeywordList
						} = res
						this.placeholder = defaultKeyword.keyword
						this.historyList = historyKeywordList.map(el => {
							return {
								text: el
							}
						})
						this.hotList = hotKeywordList.map(el => {
							return {
								text: el.keyword,
								hot: el.is_hot
							}
						})
					}
				})
			},
			onChange(val) {
				if (this.doNotShowSearchList) {
					this.doNotShowSearchList = false
					return
				}

				// 搜索框onChange事件后的初始化
				this.init()
				this.dropdownVal1 = ''
				this.dropdownVal2 = ''
				this.options2 = []
				this.hasFetchedGoodsList = false // 每次都要初始化

				// 防抖
				if (timer) {
					clearTimeout(timer)
				}

				timer = setTimeout(() => {
					// 当前输入框的值
					console.log(val)
					this.$request({
						url: 'search/helper',
						data: {
							keyword: val
						},
						successCb: res => {
							console.log(res)
							this.showMode = 2 // 搜索列表
							this.searchList = res
						}
					})
				}, 500)
			},
			onSearch(val) {
				// 当前输入框的值
				console.log(val)
				this.showGoodsList(val)
			},
			onCustom() {
				// uni.navigateBack()
				uni.switchTab({
					url: '../index/index'
				})
			},

			// 展示商品列表相关的逻辑
			showGoodsList(text) {
				this.doNotShowSearchList =
					true // 由于要把关键字赋值给搜索框，导致意外触发了搜索框的onChange事件而展示了搜索结果列表，因此用变量doNotShowSearchList来做一个逻辑判断：当搜索框有值且要展示产品列表时，不要展示搜索结果列表
				this.showMode = 3
				this.searchVal = text
				this.requestGoodsList()
			},
			// 商品请求的逻辑
			requestGoodsList() {
				// 请求商品数据
				this.$request({
					url: 'goods/list',
					data: {
						keyword: this.searchVal,
						size: 10,
						page: this.currentPage,
						sort: this.sort, // 排序依据
						order: this.dropdownVal1, // 价格的值
						categoryId: this.dropdownVal2 // 分类的值
					},
					successCb: res => {
						console.log(res)


						let {
							goodsList,
							totalPages,
							filterCategory
						} = res


						this.hasFetchedGoodsList = true // 已经获取到商品列表
						this.goodsList = [...this.goodsList, ...goodsList]
						this.totalPages = totalPages
						this.options2 = filterCategory.map(el => {
							return {
								label: el.name,
								value: el.id
							}
						})
						// 在filterCategory找有没有一项，他的checked为true，如果找得到，那么这一项的id赋值给this.dropdownVal2

						// find 找数组中第一个符合判断语句的数组项
						let checkedItem = filterCategory.find(el => {
							return el.checked
						})
						if (checkedItem) {
							this.dropdownVal2 = checkedItem.id
						}
					}
				})
			},
			// 父级监听点击标签
			clickTag(text) {
				console.log(text)
				this.showGoodsList(text)
			},
			// 删除历史记录
			onDeleteHistory() {
				this.$request({
					url: 'search/clearhistory',
					successCb: res => {
						this.handleSearchIndex()
					}
				})
			},
			// 点击搜索列表项
			clickSearchItem(text) {
				this.showGoodsList(text)
			},
			// 列表相关数据初始化
			init() {
				this.goodsList = []
				this.currentPage = 1
				this.totalPages = 0
			},
			// 按价格排序
			onChangeDropdownVal1(val) {
				console.log(val)
				this.sort = 'price'
				this.dropdownVal1 = val
				this.init()
				this.requestGoodsList()
			},
			// 按照分类排序
			onChangeDropdownVal2(val) {
				this.sort = this.sort === 'price' ? 'price' : 'id'
				this.dropdownVal2 = val
				this.init()
				this.requestGoodsList()
			}
		}
	}
</script>

<style lang="scss">
	.goods-list {
		display: flex;
		justify-content: space-between;
		flex-wrap: wrap;
		padding: 20rpx;
		background-color: #fff;

		.item {
			width: 49%;
			position: relative;
			padding-bottom: 20rpx;
			margin-bottom: 20rpx;

			.img {
				position: relative;
				width: 100%;

				// 可以让高度等于宽度
				height: 0;
				padding-top: 100%;

				.inner {
					position: absolute;
					left: 0;
					right: 0;
					top: 0;
					height: 100%;
				}
			}

			.text,
			.price {
				font-size: 28rpx;
				text-align: center;
			}

			.text {
				margin-bottom: 10rpx;
				width: 100%;
				white-space: nowrap; // 强制在同一行内显示所有文本
				text-overflow: ellipsis; // 省略号
				overflow: hidden; // 溢出隐藏
			}

			.price {
				color: darkred;
			}
		}
	}
</style>
